/*
 * @Author: 姚沈阳 11500793+yao-shenyang@user.noreply.gitee.com
 * @Date: 2023-10-13 20:36:53
 * @LastEditors: 姚沈阳 11500793+yao-shenyang@user.noreply.gitee.com
 * @LastEditTime: 2023-10-13 20:38:48
 * @FilePath: \实训二\project\src\utils\request.js
 * @Description: 
 * qq1908552310
 */
import axios from "axios";

import Qs from "qs";
const request = axios.create({
    timeout: 5000,
});

// 添加请求拦截器
request.interceptors.request.use(
    function (config: any) {
        // 在发送请求之前做些什么
        const token = window.localStorage.getItem("token");
        if (token) {
            config.headers.Authorization = token;
        }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    },
);

// 添加响应拦截器
request.interceptors.response.use(
    function (response: any) {
        // 对响应数据做点什么

        return response;
    },
    (error) => {
        // 对响应错误做些什么
        const code = error.response.status;
        switch (code) {
            case 400:
                console.log("错误的请求");
                break;
            case 401:
                console.log("请求未授权");
                break;
            case 403:
                console.log("服务器拒绝请求");
                break;
            case 404:
                console.log("请求的网页不存在");
                break;
            case 500:
                console.log("服务器内部错误");
                break;
            default:
                break;
        }
        return Promise.reject(error);
    },
);

export const getJson = (url: string, params?: any) => {
    return request.get(url, { params });
};
export const postJson = (url: string, data?: any) => {
    return request.post(url, Qs.stringify(data));
};
export const putJson = (url: string, data?: any) => {
    return request.put(url, data);
};
export const deleteJson = (url: string, data?: any) => {
    return request.delete(url, data);
};
export default request;